class code2 {
    //思路：左边选择+排序+右边选择+排序
    int[] tmp;
    int ret;
    public int reversePairs(int[] nums) {
        tmp = new int[nums.length];
        mergeSort(nums,0,nums.length-1);
        return ret;
    }
    public void mergeSort(int[] nums,int left,int right) {
        //1.出口
        if(left>=right) return ;
        //2.求中点
        int mid = (left+right)/2;
        //3.左右排序(都在左边的个数+右边的个数)
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);
        //4.合并数组(升序版)
        int cur1=left,cur2=mid+1,i=0;
        //定cur2,移动cur1
        while(cur1<=mid&&cur2<=right) {
            if(nums[cur1]<=nums[cur2]) {
                tmp[i++] = nums[cur2++];
            } else {
                ret += (right-cur2+1);
                tmp[i++] = nums[cur1++];
            }
        }
        //处理剩下元素
        while(cur1<=mid) tmp[i++] = nums[cur1++];
        while(cur2<=right) tmp[i++] = nums[cur2++];
        //5.映射
        for(int j=left;j<=right;j++) {
            nums[j] = tmp[j-left];
        }
    }
}